// 系统配置模块 - 使用Serde、bincode和toml-rs进行序列化和反序列化

use std::collections::HashMap;
use std::fs::{self, File};
use std::path::Path;
use std::io::{Read, Write};
use serde::{Serialize, Deserialize};
use log::{info, error, warn};

// 配置格式枚举
pub enum ConfigFormat {
    Json,
    Toml,
    Binary,
}

// 服务配置结构体
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ServiceConfig {
    pub enabled: bool,
    pub priority: u8,
    pub max_memory_mb: u64,
    pub auto_start: bool,
    pub capabilities: Vec<String>,
}

impl Default for ServiceConfig {
    fn default() -> Self {
        ServiceConfig {
            enabled: true,
            priority: 50,
            max_memory_mb: 256,
            auto_start: true,
            capabilities: Vec::new(),
        }
    }
}

// 显示模式配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct DisplayMode {
    pub width: u32,
    pub height: u32,
    pub refresh_rate: u32,
}

// 通道配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ChannelConfig {
    pub priority: u8,
    pub buffer_size: u32,
}

// UI通信配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct UiCommConfig {
    pub enabled: bool,
    pub shm_size_mb: u32,
    pub batch_threshold: u32,
    pub max_queue_length: u32,
    pub priority_scheduling: bool,
    pub channels: HashMap<String, ChannelConfig>,
}

// Vulkan配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct VulkanConfig {
    pub enabled: bool,
    pub validation_layers: bool,
    pub max_swapchain_images: u32,
    pub preferred_format: String,
}

// Wayland配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct WaylandConfig {
    pub enabled: bool,
    pub compositor: bool,
    pub max_connections: u32,
}

// Skia配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct SkiaConfig {
    pub enabled: bool,
    pub precision: String,
    pub cache_size_mb: u32,
}

// 图形系统配置
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct GraphicsConfig {
    pub enabled: bool,
    pub default_backend: String,
    pub hardware_acceleration: bool,
    pub vulkan: VulkanConfig,
    pub wayland: WaylandConfig,
    pub skia: SkiaConfig,
}

// 系统配置结构体
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SystemConfig {
    pub boot_services: Vec<String>,
    pub services: HashMap<String, ServiceConfig>,
    pub default_display_mode: DisplayMode,
    pub logging_level: String,
    pub max_processes: u32,
    pub memory_limit_mb: u64,
    pub kernel_parameters: HashMap<String, String>,
    pub ui_comm: UiCommConfig,
    pub graphics: GraphicsConfig,
    pub run_example_graphics_app: Option<bool>,
}

impl Default for SystemConfig {
    fn default() -> Self {
        let mut services = HashMap::new();
        
        // 为每个服务设置默认配置
        let mut mem_config = ServiceConfig::default();
        mem_config.capabilities.push("memory".to_string());
        services.insert("memory".to_string(), mem_config);
        
        let mut proc_config = ServiceConfig::default();
        proc_config.capabilities.push("cpu".to_string());
        services.insert("process".to_string(), proc_config);
        
        let mut fs_config = ServiceConfig::default();
        fs_config.capabilities.push("io".to_string());
        services.insert("filesystem".to_string(), fs_config);
        
        let mut net_config = ServiceConfig::default();
        net_config.capabilities.push("io".to_string());
        services.insert("network".to_string(), net_config);
        
        let mut gfx_config = ServiceConfig::default();
        gfx_config.capabilities.push("memory".to_string());
        gfx_config.capabilities.push("io".to_string());
        services.insert("graphics".to_string(), gfx_config);
        
        let mut vulkan_config = ServiceConfig::default();
        vulkan_config.capabilities.push("memory".to_string());
        vulkan_config.capabilities.push("io".to_string());
        services.insert("vulkan".to_string(), vulkan_config);
        
        let mut skia_config = ServiceConfig::default();
        skia_config.capabilities.push("memory".to_string());
        services.insert("skia".to_string(), skia_config);
        
        let mut wayland_config = ServiceConfig::default();
        wayland_config.capabilities.push("memory".to_string());
        services.insert("wayland".to_string(), wayland_config);
        
        let mut ipc_config = ServiceConfig::default();
        ipc_config.capabilities.push("memory".to_string());
        services.insert("ipc".to_string(), ipc_config);
        
        let mut kuikly_config = ServiceConfig::default();
        kuikly_config.capabilities.push("memory".to_string());
        services.insert("kuikly".to_string(), kuikly_config);
        
        // Shell服务默认配置
        let mut shell_config = ServiceConfig::default();
        shell_config.capabilities.push("process".to_string());
        shell_config.capabilities.push("io".to_string());
        shell_config.capabilities.push("filesystem".to_string());
        services.insert("shell".to_string(), shell_config);
        
        // 内核参数
        let mut kernel_params = HashMap::new();
        kernel_params.insert("init_level".to_string(), "2".to_string());
        kernel_params.insert("scheduler_policy".to_string(), "fair".to_string());
        kernel_params.insert("memory_pressure_threshold".to_string(), "80".to_string());
        
        // 为UI通信配置设置默认值
        let mut ui_comm_config = UiCommConfig::default();
        ui_comm_config.enabled = true;
        ui_comm_config.shm_size_mb = 32;
        ui_comm_config.batch_threshold = 10;
        ui_comm_config.max_queue_length = 1024;
        ui_comm_config.priority_scheduling = true;
        
        // 添加默认通信通道
        let mut channels = HashMap::new();
        channels.insert("main".to_string(), ChannelConfig { priority: 1, buffer_size: 4096 });
        channels.insert("input".to_string(), ChannelConfig { priority: 0, buffer_size: 2048 });
        channels.insert("render".to_string(), ChannelConfig { priority: 2, buffer_size: 8192 });
        ui_comm_config.channels = channels;
        
        // 为图形系统配置设置默认值
        let mut graphics_config = GraphicsConfig::default();
        graphics_config.enabled = true;
        graphics_config.default_backend = "vulkan".to_string();
        graphics_config.hardware_acceleration = true;
        
        // 设置Vulkan默认配置
        graphics_config.vulkan.enabled = true;
        graphics_config.vulkan.validation_layers = false;
        graphics_config.vulkan.max_swapchain_images = 3;
        graphics_config.vulkan.preferred_format = "b8g8r8a8_srgb".to_string();
        
        // 设置Wayland默认配置
        graphics_config.wayland.enabled = true;
        graphics_config.wayland.compositor = true;
        graphics_config.wayland.max_connections = 32;
        
        // 设置Skia默认配置
        graphics_config.skia.enabled = true;
        graphics_config.skia.precision = "medium".to_string();
        graphics_config.skia.cache_size_mb = 64;
        
        SystemConfig {
            boot_services: vec![
                "memory".to_string(),
                "process".to_string(),
                "filesystem".to_string(),
                "ipc".to_string(),
                "graphics".to_string(),
                "wayland".to_string(),
                "kuikly".to_string(),
                "shell".to_string(), // 添加Shell服务到启动服务列表
            ],
            services,
            default_display_mode: DisplayMode {
                width: 1920,
                height: 1080,
                refresh_rate: 60,
            },
            logging_level: "info".to_string(),
            max_processes: 128,
            memory_limit_mb: 4096,
            kernel_parameters,
        ui_comm: ui_comm_config,
        graphics: graphics_config,
        run_example_graphics_app: Some(false),
    }
    }
}

// 配置管理器
pub struct ConfigManager {
    config: SystemConfig,
    config_path: String,
    config_format: ConfigFormat,
}

impl ConfigManager {
    // 创建新的配置管理器
    pub fn new(config_path: &str, config_format: ConfigFormat) -> Self {
        ConfigManager {
            config: SystemConfig::default(),
            config_path: config_path.to_string(),
            config_format,
        }
    }
    
    // 从文件加载配置
    pub fn load(&mut self) -> Result<(), String> {
        let path = Path::new(&self.config_path);
        
        if !path.exists() {
            info!("Config file not found, creating default config at {}", self.config_path);
            return self.save();
        }
        
        match File::open(path) {
            Ok(mut file) => {
                match self.config_format {
                    ConfigFormat::Binary => {
                        let mut buffer = Vec::new();
                        if let Err(err) = file.read_to_end(&mut buffer) {
                            return Err(format!("Failed to read binary config file: {}", err));
                        }
                        
                        match bincode::deserialize(&buffer) {
                            Ok(config) => {
                                self.config = config;
                                info!("Successfully loaded binary config from {}", self.config_path);
                                Ok(())
                            },
                            Err(err) => Err(format!("Failed to parse binary config: {}", err))
                        }
                    },
                    ConfigFormat::Json => {
                        let mut contents = String::new();
                        if let Err(err) = file.read_to_string(&mut contents) {
                            return Err(format!("Failed to read JSON config file: {}", err));
                        }
                        
                        match serde_json::from_str(&contents) {
                            Ok(config) => {
                                self.config = config;
                                info!("Successfully loaded JSON config from {}", self.config_path);
                                Ok(())
                            },
                            Err(err) => Err(format!("Failed to parse JSON config: {}", err))
                        }
                    },
                    ConfigFormat::Toml => {
                        let mut contents = String::new();
                        if let Err(err) = file.read_to_string(&mut contents) {
                            return Err(format!("Failed to read TOML config file: {}", err));
                        }
                        
                        match toml::from_str(&contents) {
                            Ok(config) => {
                                self.config = config;
                                info!("Successfully loaded TOML config from {}", self.config_path);
                                Ok(())
                            },
                            Err(err) => Err(format!("Failed to parse TOML config: {}", err))
                        }
                    },
                }
            },
            Err(err) => Err(format!("Failed to open config file: {}", err))
        }
    }
    
    // 保存配置到文件
    pub fn save(&self) -> Result<(), String> {
        let path = Path::new(&self.config_path);
        
        // 确保目录存在
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                if let Err(err) = fs::create_dir_all(parent) {
                    return Err(format!("Failed to create config directory: {}", err));
                }
            }
        }
        
        match File::create(path) {
            Ok(mut file) => {
                match self.config_format {
                    ConfigFormat::Binary => {
                        match bincode::serialize(&self.config) {
                            Ok(buffer) => {
                                if let Err(err) = file.write_all(&buffer) {
                                        return Err(format!("Failed to write binary config file: {}", err));
                                    }
                                    info!("Successfully saved binary config to {}", self.config_path);
                                    Ok(())
                                },
                                Err(err) => Err(format!("Failed to serialize binary config: {}", err))
                        }
                    },
                    ConfigFormat::Json => {
                        match serde_json::to_string_pretty(&self.config) {
                            Ok(contents) => {
                                if let Err(err) = file.write_all(contents.as_bytes()) {
                                        return Err(format!("Failed to write JSON config file: {}", err));
                                    }
                                    info!("Successfully saved JSON config to {}", self.config_path);
                                    Ok(())
                                },
                                Err(err) => Err(format!("Failed to serialize JSON config: {}", err))
                        }
                    },
                    ConfigFormat::Toml => {
                        match toml::to_string_pretty(&self.config) {
                            Ok(contents) => {
                                if let Err(err) = file.write_all(contents.as_bytes()) {
                                        return Err(format!("Failed to write TOML config file: {}", err));
                                    }
                                    info!("Successfully saved TOML config to {}", self.config_path);
                                    Ok(())
                                },
                                Err(err) => Err(format!("Failed to serialize TOML config: {}", err))
                        }
                    },
                }
            },
            Err(err) => Err(format!("Failed to create config file: {}", err))
        }
    }
    
    // 获取配置
    pub fn get_config(&self) -> &SystemConfig {
        &self.config
    }
    
    // 修改配置
    pub fn update_config(&mut self, new_config: SystemConfig) {
        self.config = new_config;
    }
    
    // 获取特定服务的配置
    pub fn get_service_config(&self, service_name: &str) -> Option<&ServiceConfig> {
        self.config.services.get(service_name)
    }
    
    // 设置日志级别
    pub fn apply_logging_level(&self) {
        if let Ok(level) = self.config.logging_level.parse() {
            env_logger::Builder::new()
                .filter_level(level)
                .try_init()
                .unwrap_or_else(|e| warn!("Failed to initialize logger: {}", e));
        } else {
            warn!("Invalid logging level: {}", self.config.logging_level);
        }
    }
}